package com.aike.user_center_practice.exception;

import com.aike.user_center_practice.common.BaseResponse.BaseResponse;
import com.aike.user_center_practice.common.BaseResponse.ErrorCode;
import com.aike.user_center_practice.common.BaseResponse.ResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *解析：捕获代码中所有的异常，集中处理，让前端得到更详细的业务报错/信息
 */
@RestControllerAdvice
@ResponseBody // @RestControllerAdvice需要搭配使用
public class GlobalExceptionHandle {

    // 日志管理
    final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandle.class);

    @ExceptionHandler(BusinessException.class)
    public BaseResponse businessException(BusinessException e) {
        logger.error("businessException: " + e.getMessage(), e);
        return ResultUtils.error(e.getCode(), e.getMessage(), e.getDescription());
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse runtimeException(RuntimeException e) {
        logger.error("runtimeException", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage(), "");
    }

}
